package cn.jingyinghui.config;

import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Results;
import org.kie.api.runtime.KieContainer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

@Configuration
public class KieConfig {

    @Bean
    public KieContainer kieContainer() {
        KieServices kieServices = KieServices.Factory.get();
        KieFileSystem kieFileSystem = kieServices.newKieFileSystem();

        // 加载 .drl 文件到 KieFileSystem
        try (Reader reader = new InputStreamReader(
                getClass().getResourceAsStream("/rules/simple-rule.drl"))) {
            kieFileSystem.write("/rules/simple-rule.drl", kieServices.getResources().newReaderResource(reader));
        } catch (IOException e) {
            throw new RuntimeException("Failed to load DRL file", e);
        }

        // 构建 KieModule
        KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);
        Results results = kieBuilder.buildAll().getResults();

        if (results.hasMessages(org.kie.api.builder.Message.Level.ERROR)) {
            throw new RuntimeException("Failed to build kie base: " + results.getMessages());
        }

        // 创建并返回 KieContainer
        return kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId());
    }
}
